import Entity.Courses;
import Entity.CreatEntityManager;
import Entity.Students;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "insert",urlPatterns = {"/insert"})
public class InsertChoices extends HttpServlet {
    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        EntityManager em = CreatEntityManager.GetEntityManager();
        EntityTransaction tx = em.getTransaction();
        String stu_no = request.getParameter("stu_no");
        String name = request.getParameter("stu_name");
        String major = request.getParameter("major");
        String[] choices = request.getParameterValues("choice");
        try {
            Students now = em.find(Students.class, stu_no);
            if (now == null) {
                now = new Students(stu_no, name, major, null);
            }
            tx.begin();
            List<Courses> temp = now.getCourses();
            for (int i = 0; i < choices.length; i++) {
                Courses Ctemp = em.find(Courses.class, choices[i]);
                temp.add(Ctemp);
            }
            now.setCourses(temp);
            em.persist(now);
            tx.commit();
        } catch (Exception e) {

        } finally {
            em.close();
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("选课成功");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
